import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { status } from "@/api/user"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/401',
    component: () => import('@/views/401.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/home.vue'),
    // 路由重定向
    redirect: '/home/info-admin',
    children: [
      {
        path: 'info-admin',
        meta: { title: '管理员首页' },
        component: () => import('@/views/info-admin.vue')
      },
      {
        path: 'system-management',
        meta: { title: '系管理', permission: 1 },
        component: () => import('@/views/system-management.vue')
      },
      {
        path: 'major-management',
        meta: { title: '专业管理', permission: 2 },
        component: () => import('@/views/major/major-management.vue')
      },
      {
        path: 'class-management',
        meta: { title: '班级管理', permission: 4 },
        component: () => import('@/views/class/class-management.vue')
      },
      {
        path: 'student',
        meta: { title: '学生管理', permission: 8 },
        component: () => import('@/views/student/student.vue')
      },
      {
        path: 'teacher',
        meta: { title: '教师管理', permission: 16 },
        component: () => import('@/views/teacher/teacher.vue')
      },
      {
        path: 'course-settings',
        meta: { title: '课程设置', permission: 32 },
        component: () => import('@/views/courseset/course-settings.vue')
      },
      {
        path: 'course-arrangement',
        meta: { title: '课程修改', permission: 64 },
        component: () => import('@/views/coursearr/course-arrangement.vue')
      },
      {
        path: 'admin',
        meta: { title: '管理员管理', permission: 128 },
        component: () => import('@/views/admin/admin.vue')
      }
    ]
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // console.log(store.state.user.info.loggedIn);
  // 如果登陆了
  if (store.state.user.info.loggedIn) {
    // 如果在登录页面，直接跳转到首页
    if (to.path === '/login') {
      next('/home', () => { })
    } else {

      let ret = await status()
      if (ret.data.loggedIn) {
        if (store.state.user.info.group.indexOf(String(to.meta.permission)) !== -1 || !to.meta.permission) {
          next()
        } else {
          next('/401')
        }
      }else{
        store.commit("user/updatainfo",{})
        next('/login')
      }
    }
  } else {
    // 如果没有登录，且在登陆页，就放行
    if (to.path === '/login') {
      next()
    } else {
      // 如果没有登录，且不在登录页，就跳转到登录页
      next('/login')
    }
  }
})
export default router
